package cn.factorybox.auth.service.impl;

import cn.factorybox.auth.service.AuthService;
import cn.factorybox.client.UserClient;
import cn.factorybox.common.utils.IpUtils;
import cn.factorybox.config.JwtProperties;
import cn.factorybox.entity.UserInfo;
import cn.factorybox.model.entity.User;
import cn.factorybox.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author flypig
 * @version 1.0
 * @date 2020-03-28 12:55
 */

@Service
public class AuthServiceImpl implements AuthService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public String accredit(String uName, String uPass) {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String userIp = IpUtils.getIpAddr(request);
//        System.out.println("访问ip:" + userIp);
        // 1、 根据用户名和密码查询
        User user = this.userClient.selectUser(uName, uPass, userIp);

        // 2. 判断user
        if (user == null) {
            return null;
        }

        log.info("访问ip：{}\n 登录用户的信息：{}", userIp, user.toString());
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
            // 3. jwtUtils生产jwt类型的token
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId());
            userInfo.setCompanyId(user.getCompanyId());
            userInfo.setEmail(user.getuEmail());
            userInfo.setUsername(user.getuName());
            userInfo.setPhone(user.getuPhone());
            List<String> roles = new ArrayList<>();
            roles.add(user.getRoles());
            userInfo.setRoles(roles);
//            System.out.println(userInfo);
            return JwtUtils.generateToken(userInfo, this.jwtProperties.getKey(), this.jwtProperties.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
